package Controllers;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;
import Boundry.TestingPanel;
import Boundry.Waiting;
import Boundry.GenericTools.RequestTableListPanel;
import Controllers.GenericToolsForController.BaseClass;
import Controllers.GenericToolsForController.PDFfile;
import Controllers.GenericToolsForController.RequestMainStatusEnum;
import Controllers.GenericToolsForController.RequestStepStatusEnum;
import Controllers.GenericToolsForController.WorkerPostion;
import Entity.Report;
import Entity.ReportType;
import Entity.Request;
import Entity.Status;
import Entity.TestingFailureReport;
import Exception.ICMException;
import ServerOperation.ReportPDFWriter;
/**
 * 
 * @author G16
 *
 */
public class ExaminerController extends BaseClass
{
		
	private TestingPanel _TestingPane;            // for testing step
	private RequestTableListPanel ListofAllREquestsToBeTested;
	private List<Request> reqsTobeTested ;
	
	/*
	 * Singleton 
	 */
	private static  ExaminerController Instance = null;
	private ExaminerController(){}
	public static ExaminerController getInstance()
	{
		if(Instance == null)
		{
			Instance = new ExaminerController();
		}
		return Instance;
	}
	
	int reqid_chosed;
	private Request chosenRequest;
	private Waiting waitScreen;
	
	
	/**
	 * exmaine method 
	 */
	public void examine(){
			    
		waitScreen = new Waiting();
			    SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
					@Override
					 public Void doInBackground() 
					 {		
						
					
						
						try {
							Status [] sts= {
									new Status(RequestStepStatusEnum.EXE_PASSED,RequestMainStatusEnum.OPEN),
									new Status(RequestStepStatusEnum.TST_UTESTED_EXTENDED,RequestMainStatusEnum.OPEN),
									new Status(RequestStepStatusEnum.TST_UTESTED_EXTENDED_DENY,RequestMainStatusEnum.OPEN),
									new Status(RequestStepStatusEnum.TST_UTESTED_TIME_EXTENSION_PENDING,RequestMainStatusEnum.OPEN)	};
							
							reqsTobeTested = (ArrayList<Request>)  RequestManager.getInstance().getAllRequestToBeTested(GlobalData.worker.getId(),WorkerPostion.EXAMINER,sts);		
							
							System.out.println("size of reqs: "+reqsTobeTested.size());
							
							//Build table for the reviewed request list.
							if(reqsTobeTested.size()>0)
							{
								System.out.println(" reqsTobeTested.size() " + reqsTobeTested.size());
								System.out.println("reqsTobeTested.get(0).dataToStringArray().length " + reqsTobeTested.get(0).dataToStringArray().length);
								
								int a=reqsTobeTested.size();
								int b=reqsTobeTested.get(0).dataToStringArray().length;
								
								System.out.println(a +" " +b);
								tableData =  new String[a][b];
								
								for(int i=0; i<tableData.length ; i++)
								{
									tableData[i] = reqsTobeTested.get(i).dataToStringArray();
								}
								columnNames = reqsTobeTested.get(0).indexStringArray();
								ListofAllREquestsToBeTested = new RequestTableListPanel();
								System.out.println("ListofAllREquestsToBeTested = new RequestTableListPanel(); ");
								GlobalData.guiMangaer.switchScreen(ListofAllREquestsToBeTested);
								System.out.println("GlobalData.guiMangaer.switchScreen(ListofAllREquestsToBeTested); ");
								ListofAllREquestsToBeTested.buildTabel(columnNames,tableData);
								setListenerToViewDataPanel(ListofAllREquestsToBeTested);	
							}
							else
							{
								waitScreen.kill();
								JOptionPane.showMessageDialog(new JFrame(),"There is not request that can be tested", "",JOptionPane.DEFAULT_OPTION);
							}
						} catch (HeadlessException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						return null;
					 	}
						@Override
						public void done() 
						{
							waitScreen.kill();
							waitScreen = null;
						}
					    };
					    worker.execute();
			
	}
	
	
	/**
	 * fail testing report
	 * @param strDes
	 * @throws ICMException
	 */
	public void failTesting() throws IOException, ICMException
	{
		
			Report TestingFailureNewReport = null;
			try 
			{
				Report r = new Report();
				File file = r.buildTestingFailureReport(chosenRequest,_TestingPane.getTextArea().getText());
				PDFfile pdf = new PDFfile();
				pdf.read(file.getPath());
				System.out.print(file.getPath());
				TestingFailureNewReport = new Report(GlobalData.worker, " ", pdf, new Date(),ReportType.TESTING);
			} 
			catch (Exception e) 
			{
		        System.out.println("Error creating pdf file in testing report called from action listener testing report");
				e.printStackTrace();
			}
			if (chosenRequest!= null && TestingFailureNewReport!=null )
			{
				chosenRequest.addReport(TestingFailureNewReport); 
				JOptionPane.showMessageDialog(new JFrame(),"Testing Failure report added for request number "+chosenRequest.getRequestId(), "",JOptionPane.DEFAULT_OPTION);
				GlobalData.request = null;
				chosenRequest.changeStatus(new Status(RequestStepStatusEnum.EXE_REXECUTE,RequestMainStatusEnum.OPEN), "Testing Failed", chosenRequest.getTimetimeForExecution());
			}			

			
	}
	/**
	 * pass test
	 */
	public void passTesting()
	{
		
		chosenRequest.changeStatus(new Status(RequestStepStatusEnum.TST_PASSED,RequestMainStatusEnum.OPEN), "Testing Passed", 0);
		
	}
	
	@Override
	/*
	 * (non-Javadoc)
	 * @see Controllers.GenericToolsForController.BaseClass#actionPerformed(java.awt.event.ActionEvent)
	 */
	public void actionPerformed(ActionEvent e) 
	{

		try {
			TestingListener(e);
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		if (e.getSource() == _TestingPane.btnAskForMoreTime)
		 {	
			 this.askForMoreTime(chosenRequest);
		 
		 }
		
	}
	
	/**
	 * Listener for testing , click event
	 * @param e
	 * @throws IOException
	 */
	private void TestingListener(ActionEvent e) throws IOException {			
		
		
		if (ListofAllREquestsToBeTested!=null)
		{
			if (e.getSource() == ListofAllREquestsToBeTested.btnBack)
			{	
				GUIControllerWorker.getInstance().inizializtion();
			}
			else if (e.getSource() == ListofAllREquestsToBeTested.btnNext)
			{	
				if(ListofAllREquestsToBeTested.isChosen())
				{
					_TestingPane =  new TestingPanel();
					GlobalData.guiMangaer.switchScreen(_TestingPane);
					chosenRequest = reqsTobeTested.get(ListofAllREquestsToBeTested.getChosen());
					_TestingPane.setTxtCreationDate(chosenRequest.getDayOfCreation());
					_TestingPane.setTxtDescription(chosenRequest.getDescription());
					_TestingPane.setTxtExcuse(chosenRequest.getExecuse());
					_TestingPane.setTxtInfoSystem(chosenRequest.getInfoSystem().toString());
					_TestingPane.setTxtInitiator(chosenRequest.getInitiator().toString());
					_TestingPane.setTxtNotes(chosenRequest.getNotes());
					_TestingPane.setTxtPropChange(chosenRequest.getProposedChange());
					//_TestingPane.getBtnTestingResult().addActionListener(this); 		 //listeners
					_TestingPane.getRdbtnPassed().addActionListener(this);
					_TestingPane.getRdbtnFailed().addActionListener(this);
					
					setListenerToInputPanel(_TestingPane);
					
					SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
							@Override
							 public Void doInBackground() 
							 {
								return null;
							 }
							@Override
							public void done()
							 {
								GlobalData.guiMangaer.switchScreen(_TestingPane);
							 }
						};	
					worker.execute();
				}
				else
				{
				JOptionPane.showMessageDialog(new JFrame(),"Please select request from the list" ,"Error",JOptionPane.ERROR_MESSAGE);	
				}	
			}
			else if (e.getSource() == ListofAllREquestsToBeTested.btnRefresh)
			{	
				//ListofAllREquestsToBeTested.removeRow(0);	
			}
		}
		if(_TestingPane!=null)
		{
			 if (e.getSource() == _TestingPane.btnBack)
			{	
				GlobalData.guiMangaer.switchScreen(ListofAllREquestsToBeTested);
			}
			else if (e.getSource() == _TestingPane.btnSubnit)
			{	
							if (_TestingPane.getRdbtnPassed().isSelected())
							{	
								this.passTesting();
								JOptionPane.showMessageDialog(new JFrame(),"Request number : "+ chosenRequest.getRequestId() + " continue to closing step!! " ,"Notice",JOptionPane.INFORMATION_MESSAGE);
								GUIControllerWorker.getInstance().inizializtion();
							}		
							else if (_TestingPane.getRdbtnFailed().isSelected())
								{
										if (_TestingPane.getTextArea().getText().toString()!="")   //TODO if file was uploaded for testing failed report	
											{	
												try {
													failTesting();
												} catch (ICMException e1) {
													// TODO Auto-generated catch block
													e1.printStackTrace();
												}
												JOptionPane.showMessageDialog(new JFrame(),"Request number : "+ chosenRequest.getRequestId() + " returned to execution step!! " ,"Notice",JOptionPane.INFORMATION_MESSAGE);
												GUIControllerWorker.getInstance().inizializtion();	
											}
										else	 
											{
												JOptionPane.showMessageDialog(new JFrame(),"Please browse to add a failure testing report to request" ,"Error",JOptionPane.ERROR_MESSAGE);
											}
								}							
			else if (!_TestingPane.getRdbtnFailed().isSelected() && !_TestingPane.getRdbtnPassed().isSelected())
						{	
							JOptionPane.showMessageDialog(new JFrame(),"Please decide if the testing passed in step 3 for request number " +chosenRequest.getRequestId()  +" !! " ,"Error",JOptionPane.INFORMATION_MESSAGE);		
						}		
			
			}
			 

			 
			if(e.getSource() == _TestingPane.getRdbtnPassed())
			{   
				_TestingPane.getRdbtnPassed().setSelected(true);
				_TestingPane.getRdbtnFailed().setSelected(false);
				_TestingPane.getFailReportPanel().setVisible(false);
		 	}
			else if (e.getSource() == _TestingPane.getRdbtnFailed())
			{
				_TestingPane.getRdbtnPassed().setSelected(false);
				_TestingPane.getRdbtnFailed().setSelected(true);
				_TestingPane.getFailReportPanel().setVisible(true);
			}	
			
		}				
	
					
	}	
	
	
}

